/* FUNCION PARA SIMULAR DEVICEREADY EN NAVEGADOR*///aaa
(function StopGap() {
	function deviceready() {
		// fire off deviceready
		var e = document.createEvent('Events'); 
		e.initEvent('deviceready');
		document.dispatchEvent(e);
	}
	
	window.Cordova = {};
	deviceready();
}());
//Borrar datos locales
window.localStorage.clear();

window.setTimeout(function() {
	$(document).trigger('deviceready');
	pgReady.resolve();
}, 50);

var jqmReady = $.Deferred()
	, pgReady = $.Deferred();


//jqm ready
$(document).bind("pageinit", function() {
	console.debug('TRAMAPP:> pageinit');
	jqmReady.resolve();
});

// phonegap ready
document.addEventListener("deviceready", function(){
	console.debug('TRAMAPP:> deviceready');
	pgReady.resolve();
}, false);

// all ready :)
$.when(jqmReady, pgReady).then( function() {
	init();
});

function init() {

		var TramApp = TramApp || {};
		
		TramApp.app = (function() {
			
			var storage = window.localStorage
				, getUser = function () {
					console.debug('TRAMAPP:> getUser');
					return storage.getItem('user');
				}
				, getPass = function () {
					console.debug('TRAMAPP:> getPass');
					return storage.getItem('pass');
				}
				, getDisciplinas = function () {
					console.debug('TRAMAPP:> getDisciplinas');
					var discs = storage.getItem('discs');
					return discs ? JSON.parse(discs) : null;
				}
				, getSpells = function () {
					console.debug('TRAMAPP:> getSpells');
					var spells = storage.getItem('spells');
					return spells ?  JSON.parse(spells) : null;
				}
				, loadDiscs = function () {
					console.debug('TRAMAPP:> loadDiscs');
					var disc = getDisciplinas();
					
					if (!disc) {
						return $.ajax({
								'url' : 'http://hogwarts-chronicles.com/api/disciplinas.php',
								'dataType' : 'jsonp'
							}).done(function(data) {
								storage.setItem('discs', JSON.stringify(data.result));
							});
					} else {
//						disc = JSON.parse(disc);
						return $.Deferred().resolve();
					}
				}
				, init = function () {
					console.debug('TRAMAPP:> init');
					var dlist = $('#dlist');
					
					if($('li', dlist).length == 0){
						var discs = getDisciplinas();
						var discItem = $('<li/>').append($('<a/>').attr({
								'href' : '#new',
								'data-transition' : 'slide'
							}));
						for(var i = 0; i < discs.length; i++) {
							var clone = discItem.clone();
							$('a', clone).append(discs[i].nombre)
								.click({'value': discs[i].id}, function(event) {
									loadspells(event.data.value);
								}).append(icons[discs[i].id]);
							dlist.append(clone);
						}
						dlist.listview('refresh');
					}
					
				}
				, loadDetail = function (spell) {
					console.debug('TRAMAPP:> load details');
					$('#spellName').text(spell.nombre);
					$('#spellDesc').text(spell.descripcion);
					$('#spellLevel').text(parseInt(spell.dificultad));
//					$('#spellImg').attr('src', icons[spell.disciplina]);
				}
				, loadspells = function (id) {
					console.debug('TRAMAPP:> loadspells');
					var slist = $('#slist');
					var spells = getSpells();
					var spellItem = $('<li/>').append($('<a/>').attr({
						'href' : '#spell',
						'data-transition' : 'slide'
					}).append(icons[id]));
					slist.empty();
					
					for(var i = 0; i < spells[id].length; i++) {
						var clone = spellItem.clone();
						$('a', clone).prepend(spells[id][i].nombre)
							.click({'spell' : spells[id][i]}, function(event){
								loadDetail(event.data.spell);
						});
						slist.append(clone);
					}
					
					slist.listview('refresh');
				}
				, getSpellsById = function (i, user, pass) {
					console.debug('TRAMAPP:> getSpellsById i:' + i + ', u:' + user);
					return $.ajax({
						'url' : 'http://hogwarts-chronicles.com/api/hechizos_por_disc.php',
						'dataType' : 'jsonp',
						'data' : {
							'disc' : i,
							'usuario' : user,
							'clave' : pass
						}
					}).error(function(){
						console.log('TRAMAPP:> getSpellsById disc: ' + i + ', ERROR');
						alert('Error de autenticacion');
					}).success(function(data){
						console.log('TRAMAPP:> getSpellsById disc: ' + i + ', SUCCESS');
						var spells = getSpells() || {};
						spells[i] = data.result;
						storage.setItem('spells', JSON.stringify(spells));
					})
				}
				, showLogin = function (show) {
					console.debug('TRAMAPP:> showLogin : ' + show);
					if (show) {
						$('#login').show();
						$('#discs').hide();
					} else {
						$('#discs').show();
						$('#login').hide();
					}
				}
				, icons = (function(){
					var img = $('<img/>').addClass('ui-li-icon');
					return {
						'1': img.clone().attr('src','img/encantamientos.png'),
						'2': img.clone().attr('src','img/transformaciones.png'),
						'3': img.clone().attr('src','img/materiales.png'),
						'4': img.clone().attr('src','img/desplazamiento.png'),
						'5': img.clone().attr('src','img/ataque.png'),
						'6': img.clone().attr('src','img/elementales.png'),
						'7': img.clone().attr('src','img/sensoriales.png'),
						'8': img.clone().attr('src','img/defensa.png'),
						'9': img.clone().attr('src','img/corporales.png'),
						'11': img.clone().attr('src','img/invocaciones.png'),
						'12': img.clone().attr('src','img/artesoscuras.png')
					}
				}())
				, login = function (user, pass) {
					console.debug('TRAMAPP:> login u:' + user);
					$.when(loadDiscs())
						.done(function(){
							var disciplinas = getDisciplinas();
							var deferreds = [];
							
							for (var i = 0; i < disciplinas.length; i++) {
								deferreds.push( getSpellsById(disciplinas[i].id, user, pass) );
							}
							
							$.when.apply(window, deferreds)
								.then(function(){
									init();
									storage.setItem('user', user);
									storage.setItem('pass', pass);
									showLogin(false);
								});
						});
				};
			 
			return {
				init : init,
				loadspells : loadspells,
				getSpellsById : getSpellsById,
				login : login,
				showLogin : showLogin,
				getUser : getUser,
				getPass : getPass
			};
			
		}());
		
		
		
		
		
		(function() {
			var user = TramApp.app.getUser();
			var pass = TramApp.app.getPass();
			
			if(user && pass) {
				TramApp.app.showLogin(false);
				TramApp.app.init();
			} else {
				TramApp.app.showLogin(true);
			}
		}());
		
		$('#notif').click(function(){
			window.plugins.statusBarNotification.notify('TramApp', 'Tienes 7 hechizos nuevos.');
			navigator.notification.beep(1);
		});
		
		$('#send').click(function(){
			console.debug('TRAMAPP:> send button');
			var user = $('#user').val();
			var pass = $('#pass').val();
			
			user ? $('#userRequired').hide() : $('#userRequired').show();
			pass ? $('#passRequired').hide() : $('#passRequired').show();
			
			if (user && pass) {
				TramApp.app.login(user, pass);
			}
		});
		
//		$('.back').click(function() {
//			if ($.mobile.activePage.attr('id') == 'home') {
//				
//			} else {
//				
//			}
//		});
		
};